package engine;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;

import constans.Globals;
import constans.ResourceManager;
import controller.ObjectController;
import entity.Entity;

public class MiniMap {
	private Image background;
	private int x;
	private int y;
	private int width;
	private int height;
	private int scale;
	private int viewY;
	private int margin;
	private int screen;
	
	public MiniMap()
	{
		x = 655;
		y = 15;
		scale = 6;
		margin = 5;
		width = Globals.MAP_SIZE_Y / scale;
		height = Globals.MAP_SIZE_X / scale;
		screen = Globals.SCREEN_SIZE / scale;
		background = ResourceManager.getImage("miniMap");
	}
	public void render(GameContainer container, Graphics g) throws SlickException
	{	
		background.draw(x,y);
		g.setColor(Color.white);
		g.drawRect(x + margin, viewY + margin - screen/2, width, Globals.SCREEN_SIZE/scale);
		
		updateMap(g);
	}
	public void update(GameContainer container, int delta) throws SlickException
	{
		Input input = container.getInput();	
		if(isOn(input.getMouseX(), input.getMouseY()))
			if(input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON))
			{
				int my = input.getMouseY();
				if(my > height - screen/2)
				{
					my = height - screen;
					Map.dx = -my * scale;
				}
				else if(my < screen/2)
				{
					my = 0;
					Map.dx = -my * scale;
				}
				else Map.dx = (-my + screen/2) * scale;
			}
		
		viewY = y - Map.dx / scale + screen/2;
	}
	private boolean isOn(int mx, int my)
	{
		if(mx > x && mx < x + width && my > y && my < y + height) return true;
		return false;
	}
	private void updateMap(Graphics g)
	{
		MapMatrix map = ObjectController.getMap();
		for(int i = 0 ; i < Globals.MAP_I ; i++)
			for(int j =0 ; j < Globals.MAP_J ; j++)
				if(!map.isFieldEmpty(i, j))
				{
					Entity e = map.getEntity(i, j);
					if(e.getType() == Entity.BUILDING)
					{
						g.setColor(Color.white);
						g.fillRect(-2 + x + screen - e.getY()/scale,margin +  y+e.getX()/scale, Globals.FIELD_SIZE/scale, Globals.FIELD_SIZE/scale);
					}
					else
					{
						g.setColor(Color.red);
						g.fillOval(-2 + x + screen - e.getY()/scale,margin +  y+e.getX()/scale, Globals.FIELD_SIZE/scale, Globals.FIELD_SIZE/scale);
					}
					
						
				}
	}

}
